package com.zhu.mqsms.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    private final RedisTemplate<String, String> redisTemplate;

    public VerificationCodeService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String generateVerificationCode(String key) {
        // 生成随机验证码
        String verificationCode = generateRandomCode();
        // 将验证码存入 Redis，并设置过期时间，比如 5 分钟
        redisTemplate.opsForValue().set(key, verificationCode, 1, TimeUnit.MINUTES);
        return verificationCode;
    }

    public boolean verifyVerificationCode(String key, String code) {
        String storedCode = redisTemplate.opsForValue().get(key);
        return storedCode!= null && storedCode.equals(code);
    }

    private String generateRandomCode() {
        // 生成 6 位随机数字验证码
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        return String.valueOf(code);
    }
}